<template>
  <div class="app-container">
    <div style="display: flex; justify-content: space-between">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="addRulesClick"
            >新增补卡规则</el-button
          >
        </el-col>
      </el-row>
      <!-- 请输入补卡规则名称输入框-->
      <div>
        <el-input
          v-model="queryParams.name"
          style="max-width: 200px; margin-left: 10px"
          placeholder="请输入规则名称"
          @change="handleQuery"
        >
          <template #append>
            <el-button :icon="Search" />
          </template>
        </el-input>
      </div>
    </div>
    <el-table
      v-loading="loading"
      :data="postList"
      :default-sort="{ prop: 'name', order: 'descending' }"
    >
      <el-table-column
        label="规则名称"
        align="center"
        prop="name"
        width="180"
      />
      <el-table-column label="规则内容" align="center">
        <template #default="scope">
          <div>
            {{ scope.row.isRemedy == 0 ? "不允许补卡" : "" }}
          </div>

          <div v-if="scope.row.isRemedy != 0">
            补卡次数：每个月可提交{{ scope.row.allowNum }}次；每月的{{
              scope.row.countDayNum
            }}日起算
          </div>
          <div v-if="scope.row.isRemedy != 0">
            补卡时限：可申请最近{{ scope.row.dayLimit }}个{{
              handleDayType(scope.row.dayType)
            }}内的补卡
          </div>
          <div v-if="scope.row.isRemedy != 0">
            $补卡类型：<span v-for="item in scope.row.type" :key="item">{{
              handleType(item) + "  "
            }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="应用范围" align="center">
        <template #default="scope">
          <span
            style="margin-left: 10px"
            v-for="item in scope.row.groupNameList"
            :key="item"
            >{{ item + " " }}</span
          >
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['attendance:rule:card:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['attendance:rule:card:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修班次对话框 -->
    <el-drawer :title="title" v-model="open" direction="rtl">
      <template #default>
        <div>
          <div>
            <el-form :model="cardForm" :rules="rules" ref="postRef">
              <el-form-item label="规则名称" prop="name">
                <el-input
                  v-model="cardForm.name"
                  placeholder="请输入"
                  maxlength="30"
                  show-word-limit
                  style="width: 240px"
                />
              </el-form-item>
            </el-form>
          </div>
          <div>
            <p style="font-size: 14px">应用范围</p>
            <div style="display: flex">
              <el-select
                v-model="application"
                placeholder="请选择"
                style="width: 150px"
              >
                <el-option
                  v-for="item in options2"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-select
                multiple
                filterable
                v-model="cardForm.groupIds"
                placeholder="未设置"
                style="width: 240px; margin-left: 10px"
              >
                <el-option
                  v-for="item in groupList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </div>
          </div>
          <div>
            <p style="font-size: 14px">负责人</p>
            <el-select
              v-model="cardForm.principalId"
              placeholder="未设置"
              style="width: 240px"
            >
              <el-option
                v-for="item in principalSelectList"
                :key="item.userId"
                :label="item.nickName"
                :value="item.userId"
              />
            </el-select>
          </div>
          <div style="display: flex; align-items: center; font-size: 14px">
            <p>允许补卡</p>
            <el-switch
              v-model="isRemedySwitch"
              size="small"
              style="margin-left: 10px"
            />
          </div>
        </div>
        <!-- 允许补卡隐藏内容 -->
        <div style="font-size: 14px" v-if="isRemedySwitch == true">
          <div>
            <p>补卡次数</p>
            <div>
              <span>每月可提交</span>
              <el-input-number
                v-model="cardForm.allowNum"
                :min="1"
                :max="10"
                controls-position="right"
                style="width: 100px; margin-left: 10px"
              />
              <span style="margin-left: 10px">次补卡,</span>
              <span style="margin-left: 10px">每月的</span>
              <el-select
                v-model="cardForm.countDayNum"
                placeholder="请选择"
                style="width: 100px; margin-left: 10px"
              >
                <el-option
                  v-for="day in 30"
                  :key="day"
                  :label="`${day}日`"
                  :value="day"
                >
                </el-option>
              </el-select>
              <span style="margin-left: 10px">起算</span>
            </div>
          </div>
          <div>
            <p>补卡时限</p>
            <div>
              <span style="margin-left: 10px">可申请过去</span>
              <el-input-number
                v-model="cardForm.dayLimit"
                :min="1"
                :max="30"
                controls-position="right"
                style="margin-left: 10px; width: 100px"
              />
              <el-select
                v-model="cardForm.dayType"
                placeholder="请选择"
                style="width: 100px; margin-left: 10px"
              >
                <el-option
                  v-for="item in dayTypeOPtion"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <span style="margin-left: 10px">内的补卡</span>
            </div>
          </div>
          <div>
            <p style="font-size: 14px">补卡类型</p>
            <el-checkbox-group v-model="cardForm.type" style="font-size: 14px">
              <el-checkbox
                :label="item.name"
                :value="item.id"
                v-for="item in typeOptions"
                :key="item.id"
              />
            </el-checkbox-group>
          </div>
        </div>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-drawer>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>
<script setup>
import {
  cardListPost,
  AddCardPost,
  DelCardPost,
  updateCardPost,
  getCardPost,
} from "@/api/attendance/card";
import { getGroupListApi } from "@/api/attendance/attendance";
import { getOrgSearchAgApi } from "@/api/attendance/shift";
import { Search } from "@element-plus/icons-vue";
import { ref, watch } from "vue";
const { proxy } = getCurrentInstance();
// 新增补卡规则按钮嵌套弹框中下拉选择框
const application = ref(1);
const postList = ref([]);
const open = ref(false);
const loading = ref(true);
const total = ref(0);
const title = ref("");
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: "",
  },
  rules: {
    name: [{ required: true, message: "规则名称不能为空", trigger: "blur" }],
  },
});

const isRemedySwitch = ref(false);
const cardForm = ref({
  name: "",
  groupIds: [],
  principalId: "", //接口是单选，需求多选
  isRemedy: 0, //是否允许补卡 0否 1是
  allowNum: undefined, //每月可提交补卡次数
  countDayNum: undefined, //每月的xx号起算
  dayLimit: undefined, //补卡时间限制,可申请过去xx天的
  dayType: undefined, //1：自然日 2：工作日
  type: undefined, //补卡类型集合 1：缺卡 2：迟到 3：早退 4：正常
});

const { queryParams, rules } = toRefs(data);
onMounted(() => {
  getList();
});

// 应用范围下拉框option
const options2 = [
  {
    value: 1,
    label: "考勤组",
  },
];

// 补卡时限日期选择
const dayTypeOPtion = [
  {
    value: 1,
    label: "自然日",
  },
  {
    value: 2,
    label: "工作日",
  },
];

const typeOptions = ref([
  {
    id: 1,
    name: "缺卡",
  },
  {
    id: 2,
    name: "迟到",
  },
  {
    id: 3,
    name: "早退",
  },
  {
    id: 4,
    name: "正常",
  },
]);

/**
 * 重置需补卡部分的参数
 */
const resetDepartment = () => {
  cardForm.value.allowNum = undefined;
  cardForm.value.countDayNum = undefined;
  cardForm.value.dayLimit = undefined;
  cardForm.value.dayType = undefined;
  cardForm.value.type = undefined;
};

watch(
  () => isRemedySwitch.value,
  (newValue) => {
    if (newValue == true) {
      cardForm.value.isRemedy = 1;
    } else if (newValue == false) {
      cardForm.value.isRemedy = 0;
      resetDepartment();
    }
  },
  { deep: true, immediate: true }
);

const groupList = ref([]);
/**
 * 获取所有考勤组
 */
const getGroupList = () => {
  getGroupListApi().then((res) => {
    groupList.value = res.data;
  });
};
getGroupList();

const principalSelectList = ref([]);
/**
 * 获取有管理考勤打卡资格的用户信息
 */
const getOrgSearchAg = () => {
  getOrgSearchAgApi().then((res) => {
    principalSelectList.value = res.data;
  });
};
getOrgSearchAg();

/** 查询补卡规则列表 */
function getList() {
  loading.value = true;
  cardListPost(queryParams.value).then((response) => {
    postList.value = response.rows;
    total.value = Number(response.total);
    loading.value = false;
  });
}

/**
 * 按名称搜索补卡规则
 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  cardForm.value = {
    name: "",
    groupIds: [],
    principalId: "",
    isRemedy: 0,
    allowNum: undefined,
    countDayNum: undefined,
    dayLimit: undefined,
    dayType: undefined,
    type: undefined,
  };
  proxy.resetForm("postRef");
}

/** 新增按钮操作 */
function addRulesClick() {
  reset();
  open.value = true;
  title.value = "新增补卡规则";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const postId = row.id;
  getCardPost(postId).then((response) => {
    cardForm.value = {
      id: response.data.id,
      name: response.data.name,
      groupIds: response.data.groupVoList
        ? response.data.groupVoList.map((item) => {
            return item.id;
          })
        : [],
      principalId: response.data.principalId || "",
      isRemedy: response.data.isRemedy || 0,
      allowNum: response.data.allowNum || undefined,
      countDayNum: response.data.countDayNum || undefined,
      dayLimit: response.data.dayLimit || undefined,
      dayType: response.data.dayType || undefined,
      type: response.data.type || undefined,
    };
    cardForm.value.groupIds = cardForm.value.groupIds.map((v) => String(v));

    cardForm.value.isRemedy == 1
      ? (isRemedySwitch.value = true)
      : (isRemedySwitch.value = false);
    open.value = true;
    title.value = "编辑补卡规则";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["postRef"].validate((valid) => {
    if (valid) {
      if (cardForm.value.id != undefined) {
        updateCardPost(cardForm.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        AddCardPost(cardForm.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const remedyRuleId = row.id;
  proxy.$modal
    .confirm('是否确认删该补卡规则"' + row.name + '"的数据项？')
    .then(function () {
      return DelCardPost(remedyRuleId);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/**
 * 计算表格应用范围
 * @param val
 */
const handleGroupIdsShow = (val) => {
  return (
    groupList.value.filter((item) => item.id == val)[0] &&
    groupList.value.filter((item) => item.id == val)[0].name
  );
};

/**
 * 计算表格中补卡类型
 * @param val
 */
const handleType = (val) => {
  return (
    typeOptions.value.filter((item) => item.id == val)[0] &&
    typeOptions.value.filter((item) => item.id == val)[0].name
  );
};

/**
 * 计算表格中补卡时限
 *
 * @param val
 */
const handleDayType = (val) => {
  if (val == 1) {
    return "工作日";
  } else if (val == 2) {
    return "自然日";
  } else {
    return "未知";
  }
};

getList();
</script>
<style scoped>
.el-form-item {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
:deep(.el-drawer__header) {
  border-bottom: 1px solid gainsboro;
  height: 60px;
  margin-bottom: -5px;
}
:deep(.el-dialog__header) {
  margin-top: -20px;
}
.xztj {
  display: flex;
  flex-direction: column;
  margin-top: 10px;
  :deep(.el-radio-group) {
    display: flex !important;
    flex-direction: column;
    align-items: flex-start !important;
  }
}
.xx {
  position: relative;
  top: -80px;
}
</style>
